package com.linjing.demo.message.mq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.*;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

@Component
public class MQProducer {

    private DefaultMQProducer producer;

    private TransactionMQProducer transactionMQProducer;

    private String nameAddr = "192.168.146.138:9876;192.168.146.134:9876;192.168.146.128:9876;192.168.146.135:9876";

    private String topicName = "myTopic";


    @PostConstruct
    public void init() throws MQClientException {
        //做mq producer的初始化
        System.out.println("---------初始化producer----------");
        producer = new DefaultMQProducer("MyGroup");
        producer.setNamesrvAddr(nameAddr);
        producer.start();

        transactionMQProducer = new TransactionMQProducer("transaction_MyGroup");
        transactionMQProducer.setNamesrvAddr(nameAddr);
        transactionMQProducer.start();
        transactionMQProducer.setTransactionListener(new TransactionListener() {
            @Override
            public LocalTransactionState executeLocalTransaction(Message message, Object o) {
                // 真正要做的事 创建订单
                String jsonString = new String(message.getBody());
                try {
                    System.out.println(">>>>>>>>>>>>>>>>>>>>");
                    System.out.println("业务处理");
                } catch (Exception e) {
                    e.printStackTrace();
                    // 回滚事务记录
                    System.out.println(">>>>>>>>>>>>>>>>>>>>>>>");
                    System.out.println("事务回滚");
                    return LocalTransactionState.ROLLBACK_MESSAGE;
                }
                return LocalTransactionState.COMMIT_MESSAGE;
            }

            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
                // 根据是否扣减库存成功，来判断要返回 COMMIT, ROLLBACK 还是继续 UNKNOWN
                String jsonString = new String(messageExt.getBody());
                System.out.println("事务消息检查回调 :" + jsonString);
                Map<String, Object> map = JSON.parseObject(jsonString, Map.class);
                System.out.println(">>>>>>>>>>>>>>>>>>>>");
                System.out.println("条件判断");
                return LocalTransactionState.COMMIT_MESSAGE;
                //return LocalTransactionState.ROLLBACK_MESSAGE;
            }
        });
    }


    /**
     * 同步库存扣减消息
     */
    public boolean asyncReduceStock(Integer itemId, Integer amount) {
        Map<String, Object> bodyMap = new HashMap<>(2);
        bodyMap.put("itemId", itemId);
        bodyMap.put("amount", amount);
        Message message = new Message(topicName, "TagA", String.valueOf(System.nanoTime()),
                JSON.toJSON(bodyMap).toString().getBytes(Charset.forName("UTF-8")));
        try {
            SendResult result = producer.send(message);
            System.out.println("发送减库存消息成功: " + result);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 同步库存扣减消息
     */
    public boolean transactionAsyncReduceStock(Integer userId, Integer itemId, Integer promId, Integer amount, String stockLogId) {
        Map<String, Object> bodyMap = new HashMap<>(2);
        bodyMap.put("itemId", itemId);
        bodyMap.put("amount", amount);
        bodyMap.put("stockLogId", stockLogId);
        Map<String, Object> argsMap = new HashMap<>(2);
        argsMap.put("itemId", itemId);
        argsMap.put("amount", amount);
        argsMap.put("userId", userId);
        argsMap.put("promId", promId);
        argsMap.put("stockLogId", stockLogId);
        Message message = new Message(topicName, "increase", String.valueOf(System.nanoTime()),
                JSON.toJSON(bodyMap).toString().getBytes(Charset.forName("UTF-8")));
        try {
            System.out.println("发送事务减库存消息" + JSONObject.toJSONString(bodyMap));
            TransactionSendResult result = transactionMQProducer.sendMessageInTransaction(message, argsMap);
            System.out.println("发送事务减库存消息成功，返回结果: " + result.getLocalTransactionState() + " " + result);
            if (result.getLocalTransactionState() == LocalTransactionState.COMMIT_MESSAGE) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }
}
